#
# @author Wójcik Karol <wojcikk@student.agh.edu.pl>
# @licence http://www.gnu.org/copyleft/gpl.html GNU/GPL
#

class MajorsController < ApplicationController
layout 'standard'
before_filter :login_required, :authorize
  
  def authorize
    if @session['user'].role != "admin"
        redirect_back_or_default :controller => "error", :action => "info"
    end
  end

  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @major_pages, @majors = paginate :majors, :per_page => 10
    
    sortby = params['sortby']
    case sortby
    when "name"
	     @majors = Major.find(:all, :order => "name")
    when "study_type"
	     @majors = Major.find(:all, :order => "study_type_id")
    when "faculty"
       @majors = Major.find(:all, :order => "faculty_id")
    else
	     @majors = Major.find(:all)
    end
  
  end

  def show
    @major = Major.find(params[:id])
    @majors = Major.find(:all, :order => "name")
  end

  def new
    @major = Major.new
    @majors = Major.find(:all, :order => "name")
  end

  def create
    @major = Major.new(params[:major])
    @majors = Major.find(:all, :order => "name")
    if @major.save
      flash[:notice] = 'Major was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @major = Major.find(params[:id])
    @majors = Major.find(:all, :order => "name")  
  end

  def update
    @major = Major.find(params[:id])
    @majors = Major.find(:all, :order => "name")
    if @major.update_attributes(params[:major])
      flash[:notice] = 'Major was successfully updated.'
      redirect_to :action => 'show', :id => @major
    else
      render :action => 'edit'
    end
  end

  def destroy
    @subjects = Subject.find(:all, :conditions => ["major_id = ?", params[:id]])
    if @subjects.blank?
      Major.find(params[:id]).destroy
      redirect_to :action => 'list'
    else
      redirect_to :controller => 'error', :action => 'major', :code => 'subjects', :id => params[:id]
    end
  end
end
